package com.gl.admin.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gl.admin.common.LoginBody;
import com.gl.admin.entity.SysUser;
import com.gl.admin.service.SysUserService;
import com.gl.admin.common.HttpsStatus;
import com.gl.admin.common.Result;
import com.gl.admin.utils.TokenUtils;
import com.gl.admin.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 用户管理前端控制器
 * </p>
 *
 * @author 晚风
 * @since 2023-03-23
 */
@RestController
@RequestMapping("/api/user")
@Api("用户管理")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;


    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginBody loginBody) {
        //获取用户名
        String username = loginBody.getUsername();
        //获取用户密码
        String password = loginBody.getPassword();
        //验证用户名是否为空
        if(StrUtil.isBlank(username)) {
            return Result.error(HttpsStatus.CODE_500,"用户名不能为空");
        }
        //验证密码是否为空
        if(StrUtil.isBlank(password)) {
            return Result.error(HttpsStatus.CODE_500,"用户密码不能为空");
        }
        //构建查询条件
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
        //判断用户名是否存在
        if (!StrUtil.isBlank(username)) {
            queryWrapper.eq("username", username);
        }
        //判断用户密码
        if (!StrUtil.isBlank(password)) {
            //把密码转成md5进行加密处理
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            queryWrapper.eq("password", password);
        }
        //根据条件查询
        SysUser one = getOne(queryWrapper);
        //如果用户不存在
        if (one == null) {
            //返回空
            return null;
        }
        UserVo vo = new UserVo();
        BeanUtil.copyProperties(one, vo, true);
        //获取token
        String token = TokenUtils.genToken(String.valueOf(one.getId()), one.getPassword());
        //设置token
        vo.setToken(token);
        //判断用户状态
        if ("0".equals(vo.getState())) {
            return Result.error(HttpsStatus.CODE_500,"该用户已被禁用");
        }
        return Result.success("登录成功",vo);
    }

    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        request.getSession().removeAttribute("userId");
        request.getSession().removeAttribute("employeeId");
        return Result.success("退出成功");
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public Result register(@RequestBody SysUser sysUser) {
        if (StrUtil.isBlank(sysUser.getUsername())) {
            return Result.error(HttpsStatus.CODE_500,"账号不能为空");
        }
        if (StrUtil.isBlank(sysUser.getPassword())) {
            return Result.error(HttpsStatus.CODE_500,"密码不能为空");
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
        queryWrapper.eq("username", sysUser.getUsername());
        SysUser one = getOne(queryWrapper);
        if (one != null) {
            return Result.error(HttpsStatus.CODE_500,"账号已存在");
        }
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        sysUser.setRole("ROLE_GENERAL");
        sysUserService.save(sysUser);
        return Result.success("注册成功",null);



    }

    @ApiOperation("添加/更新")
    @PostMapping("/save")
    public Result save(@RequestBody SysUser sysUser) {
        //判断用户名是否存在
        if (StrUtil.isBlank(sysUser.getUsername())) {
            //不存在就返回
            return Result.error(HttpsStatus.CODE_500,"用户名称不能为空");
        }
        //判断用户昵称是否存在
        if (StrUtil.isBlank(sysUser.getNickname())) {
            //不存在就返回
            return Result.error(HttpsStatus.CODE_500,"用户昵称不能为空");
        }
        //判断用户角色标识是否存在
        if (StrUtil.isBlank(sysUser.getRole())) {
            //不存在就返回
            return Result.error(HttpsStatus.CODE_500,"角色标识不能为空");
        }
        if (StrUtil.isBlank(sysUser.getState())) {
            return Result.error(HttpsStatus.CODE_500,"用户状态不能为空");
        }
        if (sysUser.getId() == null) {
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
            queryWrapper.eq("username", sysUser.getUsername());
            SysUser one = getOne(queryWrapper);
            if (one != null) {
                return Result.error(HttpsStatus.CODE_500,"账号已存在");
            }
            sysUser.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            sysUserService.save(sysUser);
        }else {
            SysUser one = sysUserService.getById(sysUser.getId());
            sysUser.setPassword(one.getPassword());
            sysUserService.updateById(sysUser);
        }
        return Result.success("成功",null);
    }


    @ApiOperation("根据id获取用户信息")
    @GetMapping("/getUserById")
    public Result getUserById(@RequestParam String id){
        SysUser sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            return Result.error(HttpsStatus.CODE_500,"用户不存在");
        }else {
            return Result.success("登录成功", sysUser);
        }

    }

    /**
     * 根据queryWrapper 条件从数据库中查询用户数据
     * @param queryWrapper 构造查询条件
     * @return
     */
    private SysUser getOne(QueryWrapper<SysUser>  queryWrapper) {
        return sysUserService.getOne(queryWrapper);
    }
}

